package ch.zbw.sysventory.agent.scanner.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.EnumVariant;
import com.jacob.com.Variant;

import ch.zbw.sysventory.transport.model.NetworkAdapter;

public class NetworkAdapterScanner {

	Logger logger = Logger.getRootLogger();

	public List<NetworkAdapter> getNetworkAdapters() {
		List<NetworkAdapter> networkAdapters = new ArrayList<NetworkAdapter>();

		try {
			ActiveXComponent axWMI = new ActiveXComponent(String.format("winmgmts:\\\\%s\\root\\CIMV2", "localhost"));
			Variant vCollection = axWMI.invoke("ExecQuery", new Variant("SELECT * FROM Win32_NetworkAdapterConfiguration"));

			EnumVariant enumVariant = new EnumVariant(vCollection.toDispatch());
			Dispatch item = null;
			while (enumVariant.hasMoreElements()) {
				item = enumVariant.nextElement().toDispatch();

				if ("true".equals(Dispatch.call(item, "IPEnabled").toString())) {
					NetworkAdapter networkAdapter = new NetworkAdapter();

					networkAdapter.setDefaultGateway(Dispatch.call(item, "DefaultIPGateway").toString().trim());
					networkAdapter.setDhcpServer(Dispatch.call(item, "DHCPServer").toString().trim());
					networkAdapter.setIpAddress(Dispatch.call(item, "IPAddress").toString().trim());
					networkAdapter.setMacAddress(Dispatch.call(item, "MACAddress").toString().trim());
					networkAdapter.setName(Dispatch.call(item, "Description").toString().trim());
					networkAdapter.setSubnet(Dispatch.call(item, "IPSubnet").toString().trim());

					networkAdapters.add(networkAdapter);
				}
			}
		} catch (Exception e) {
			logger.error("Cannot read network adapters: " + e.getMessage(), e);
		}

		return networkAdapters;
	}

}
